package cyou.breathe.dynamictp.config.nacos.cloud.starter.refresher;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import cyou.breathe.dynamictp.config.common.starter.refresher.AbstractDynamicThreadPoolRefresher;
import cyou.breathe.dynamictp.core.executor.support.BlockingQueueTypeEnum;
import cyou.breathe.dynamictp.core.notification.service.NotifierDispatcher;
import cyou.breathe.dynamictp.core.toolkit.ThreadPoolExecutorBuilder;
import cyou.breathe.dynamictp.core.config.BootstrapConfigProperties;
import cyou.breathe.dynamictp.spring.base.support.ApplicationContextHolder;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;

/**
 * Nacos Cloud 版本刷新处理器
 * @author: breathe
 * @createTime: 2025-09-14
 */
@Slf4j(topic = "BreatheThreadConfigRefresher")
public class NacosCloudRefresherHandler extends AbstractDynamicThreadPoolRefresher {

    private ConfigService configService;

    public NacosCloudRefresherHandler(BootstrapConfigProperties properties, NotifierDispatcher notifierDispatcher) {
        super(properties, notifierDispatcher);
        configService = ApplicationContextHolder.getBean(NacosConfigProperties.class).configServiceInstance();
    }

    @Override
    public void registerListener() throws NacosException {
        BootstrapConfigProperties.NacosConfig nacosConfig = properties.getNacos();
        configService.addListener(
                nacosConfig.getDataId(),
                nacosConfig.getGroup(),
                new Listener() {

                    @Override
                    public Executor getExecutor() {
                        return ThreadPoolExecutorBuilder.builder()
                                .corePoolSize(1)
                                .maximumPoolSize(1)
                                .keepAliveTime(9999L)
                                .workQueueType(BlockingQueueTypeEnum.SYNCHRONOUS_QUEUE)
                                .threadFactory("clod-nacos-refresher-thread_")
                                .rejectedHandler(new ThreadPoolExecutor.CallerRunsPolicy())
                                .build();
                    }

                    @Override
                    public void receiveConfigInfo(String configInfo) {
                        refreshThreadPoolProperties(configInfo);
                    }
                });

        log.info("动态线程池刷新, 成功添加nacos监听器. data-id: {}, group: {}", nacosConfig.getDataId(), nacosConfig.getGroup());
    }
}